package com.molin;

import com.molin.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

@WebServlet("/addStudentServlet")
public class AddStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求头参数
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String score = req.getParameter("score");
        Student st=new Student(name,Integer.parseInt(age),Integer.parseInt(score));
        //将学生信息写入到D:\stu.txt下（追加）
        BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\stu.txt",true));
        bw.write(st.getName()+","+st.getAge()+","+st.getScore());
        bw.newLine();
        bw.close();
        //定时刷新功能，2秒后跳转到首页
        resp.getWriter().write("添加成功！2秒后跳转到首页~");
        resp.setHeader("Refresh","2;URL=/stu/index.jsp");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
